package eiisan.config.security.service;

import eiisan.config.security.util.AuthorityUtil;
import eiisan.dao.result.user.UserDetail;
import eiisan.service.user.AuthorityService;
import eiisan.util.model.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 验证信息获取服务
 */
@Service("eiisanDTS")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {
    /**
     * 用户授权服务
     */
    @Autowired
    private AuthorityService authorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<UserDetail> result = authorityService.getUserDetailByUsername(username);
        if (Result.isNotSuccess(result)) {
            throw new UsernameNotFoundException(result.getMsg());
        }
        UserDetail userDetail = result.getData();
        return new User(userDetail.getName(), userDetail.getPassword(), AuthorityUtil.make(userDetail
                .getPermissions()));
    }
}
